package com.computec.tray;



/*
 * Email.java
 *
 * Created on 5 de julio de 2006, 17:52
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */



import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import com.computec.tray.constantes.ConstantesGenerales;


public class Email {
    
    protected static Email email;
    protected static String MAIL_SMTP_HOST;
    protected static String MAIL_SMTP_PORT;
    
    /** Creates a new instance of Email */
    protected Email() {
    	ConstantesGenerales cons=ConstantesGenerales.getInstance();
		//mailSmtpHost=172.24.15.155

		//mailSmtpPort=25

        this.MAIL_SMTP_HOST =cons.MAIL_SMTP_HOST;
        this.MAIL_SMTP_PORT = cons.MAIL_SMTP_PORT;
    }
    
    public static Email getInstance() {
        if (email == null) {
            email = new Email();
        }
        return email;
    }
    
    public void sendEmail(EmailDto dto) throws EmailException {
        boolean debug = false;
        Properties properties = new Properties();
        properties.put("mail.smtp.host", this.MAIL_SMTP_HOST);
        properties.put("mail.smtp.port", this.MAIL_SMTP_PORT);
        Session session = Session.getDefaultInstance(properties, null);
        session.setDebug(debug);
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            InternetAddress internetAddressFrom = new InternetAddress(dto.getFrom());
            mimeMessage.setFrom(internetAddressFrom);
            List recipients = dto.getRecipients();
            InternetAddress[] internetAddressTo = new InternetAddress[recipients.size()];
            Iterator iterator = recipients.iterator();
            int index = 0;
            while (iterator.hasNext()) {
                String to = (String) iterator.next();
                internetAddressTo[index++] = new InternetAddress(to);
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo);
            mimeMessage.setSubject(dto.getSubject());            
            Multipart multipart = new MimeMultipart();
            MimeBodyPart mimeBodyPartText = new MimeBodyPart();
            mimeBodyPartText.setText(dto.getMessage());
            multipart.addBodyPart(mimeBodyPartText);
          //  List attachments = dto.getAttachments();
           // if (attachments != null && !attachments.isEmpty()) {
          //      Iterator iteratorAttachments = attachments.iterator();
          //      while (iteratorAttachments.hasNext()) {
          //          RespuestaArchivoDto attachment = (RespuestaArchivoDto) iteratorAttachments.next();
          //          MimeBodyPart mimeBodyPartAttachment = new MimeBodyPart();
          //          FileDataSource fileDataSource = new FileDataSource(attachment.getPathArchivo() + attachment.getNombreArchivo());
          //          mimeBodyPartAttachment.setDataHandler(new DataHandler(fileDataSource));
          //          mimeBodyPartAttachment.setFileName(attachment.getNombreArchivo());
          //          multipart.addBodyPart(mimeBodyPartAttachment);
          //      }
          //  }
            mimeMessage.setContent(multipart);
            Transport transport = session.getTransport("smtp");
            transport.connect(this.MAIL_SMTP_HOST, null, null);
            mimeMessage.saveChanges();
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            transport.close();
        }
        catch (NoSuchProviderException nspe) {
            throw new EmailException("Email:sendEmail: " + nspe.toString(), nspe);
        }
        catch (AddressException ae) {
           throw new EmailException("Email:sendEmail: " + ae.toString(), ae);
        }
        catch (MessagingException me) {
            throw new EmailException("Email:sendEmail: " + me.toString(), me);
        }
        catch (Exception e) {
            throw new EmailException("Email:sendEmail: " + e.toString(), e);
        }
    }
    
    public void readMail(){
    	  /*
    		      import java.util.*;
    		      import javax.activation.*;
    		      import javax.mail.*;
    		      import javax.mail.internet.*;
    		      import javax.naming.*;
    		      
    		*/
    	/*
    	 boolean debug = false;
    	 Properties properties = new Properties();
         properties.put("mail.smtp.host", this.MAIL_SMTP_HOST);
         properties.put("mail.smtp.port", this.MAIL_SMTP_PORT);
         Session session = Session.getDefaultInstance(properties, null);
         session.setDebug(debug);*/
        /*
    		      InitialContext ic = new InitialContext();
    		      String snName = "java:comp/env/mail/MyMailSession";
    		      Session session = (javax.mail.Session)ic.lookup(snName);*/
       
    	Properties props = new Properties();
       
      //   String username = "fsanchez";
       //  String password = "61077643806";
         String provider = "pop3";

         int start = 1;
         int end =1;

         
	      try {
	    	 
	    	  Session session = Session.getDefaultInstance(props, new MailAuthenticator());
	    	 // Session session = Session.getDefaultInstance(props, null);
	          Store store = session.getStore(provider);
	          store.connect("computecnew.redcorp.computec.com", null, null);
	          //store.connect(this.MAIL_SMTP_HOST, username, password);
	       
		// Store store = session.getStore();
		 //store.connect("computecnew.redcorp.computec.com", "fsanchez", "61077643806");
	//	 store.connect( this.MAIL_SMTP_HOST, "fsanchez", "61077643806");
		
	      /*Folder inbox = store.getFolder("INBOX");
	      if (inbox == null) {
	          System.out.println("No INBOX");
	          System.exit(1);
	        }
	        inbox.open(Folder.READ_ONLY);*/

	        
	        Folder folder = store.getFolder("INBOX");
	        if (folder == null || !folder.exists()) {
	          System.out.println("Invalid folder: " + folder.getName());
	          System.exit(1);
	        }

	        folder.open(Folder.READ_WRITE);

	        int count = folder.getMessageCount();
	        if (count == 0) { // No messages in the source folder
	          System.out.println(folder.getName() + " is empty");
	          // Close folder, store and return
	          folder.close(false);
	          store.close();
	          return;
	        }

	        // Open destination folder, create if reqd
	        Folder dfolder = store.getFolder("FAIL");
	        if (!dfolder.exists())
	          dfolder.create(Folder.HOLDS_MESSAGES);

	        if (end == -1)
	          end = count;

	        // Get the message objects to copy
	        Message[] msgs = folder.getMessages(start, end);
	        System.out.println("Moving " + msgs.length + " messages");

	        if (msgs.length != 0) {
	          folder.copyMessages(msgs, dfolder);
	          folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);

	          // Dump out the Flags of the moved messages, to insure that
	          // all got deleted
	          for (int i = 0; i < msgs.length; i++) {
	            if (!msgs[i].isSet(Flags.Flag.DELETED))
	              System.out.println("Message # " + msgs[i] + " not deleted");
	          }
	        }
	        
	        // Close folders and store
	        folder.close(false);
	        store.close();
/*
	        
	      Message[] messages = inbox.getMessages();
	      for (int i = 0; i < messages.length; i++) {
	          System.out.println("Message " + (i + 1));
	          if(!messages[i].isSet(Flags.Flag.SEEN)){
	        	  messages[i].writeTo(System.out);
	          }	          
	          messages[i].setFlag(Flags.Flag.SEEN,true);
	        //  System.out.println("SUBJECT:"+messages[i].getSubject());
	        /*  System.out.println("Message " + (i + 1));

	          System.out.println("From: " + InternetAddress.toString(messages[i].getFrom()));
	          System.out.println("Reply-to: " + InternetAddress.toString(messages[i].getReplyTo()));
	          String to = InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.TO));
	          System.out.println("To: " + to);
	          String cc = InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.CC));
	          System.out.println("Cc: " + cc);
	          String bcc = InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.BCC));
	          System.out.println("Bcc: " + bcc);
	          System.out.println("Subject: " + messages[i].getSubject());
	          System.out.println("Sent: " + messages[i].getSentDate());
	          System.out.println("Received: " + messages[i].getReceivedDate());
	          */
	      /*  }
	       inbox.close(false);
	        store.close();*/
	        
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*catch (IOException ez) {
			// TODO Auto-generated catch block
			ez.printStackTrace();
		}*/


    }
    
    public static void main(String[] arg){
    	Email mail=Email.getInstance();
    	mail.readMail();
    	
    }
    
    class MailAuthenticator extends Authenticator {

    	  public MailAuthenticator() {
    	  }

    	  public PasswordAuthentication getPasswordAuthentication() {
    	    return new PasswordAuthentication("fsanchez", "61077643806");
    	  }
    }
}
